package ar.edu.itba.it.pdc.nio;

import java.nio.ByteBuffer;
import java.util.LinkedList;
import java.util.Queue;

import org.apache.log4j.Logger;

import ar.edu.itba.it.pdc.configuration.ProxyConfigurationLoader;

public class ByteBufferPool {

	
	private static final ByteBufferPool INSTANCE = new ByteBufferPool();

	Queue<ByteBuffer> pool = new LinkedList<ByteBuffer>();
	private int count = 0;
	
	private int cant = ProxyConfigurationLoader.getInstance().getValueAsInteger("buffer_cant");
	private int size = ProxyConfigurationLoader.getInstance().getValueAsInteger("buffer_size");
	private int max = ProxyConfigurationLoader.getInstance().getValueAsInteger("buffer_max");
	
	private Logger logger = Logger.getLogger(ByteBufferPool.class);

	
	private ByteBufferPool() {
		for (int i = 0; i < cant; i++) {
			pool.add(ByteBuffer.allocate(size));
		}
	}
	
	public static ByteBufferPool getInstance(){
		return INSTANCE;
	}
	
	public ByteBuffer getByteBuffer() throws MemoryAllocationLimitHited {
		count ++;
		if(!pool.isEmpty()){
			return pool.poll();
		} else if(count <= max){
			return ByteBuffer.allocate(size);
		} else {
			logger.error("Maximum memory allocation level reached.");
			throw new MemoryAllocationLimitHited();
		}
	}
	
	public void retriveByteBuffer(ByteBuffer bb){
		count --;
		if(count <= cant){
			bb.clear();
			pool.add(bb);
		}
	}
}
